from django.db import models
from django.contrib.auth.models import User
from django.utils.html import strip_tags
from django.utils.text import slugify
from django.urls import reverse
from markdown.extensions.toc import TocExtension
import markdown


# Create your models here.

class Tag(models.Model):
    id = models.AutoField(primary_key=True, verbose_name="标签ID")
    name = models.CharField(max_length=20, verbose_name="标签名", unique=True)

    def __str__(self):
        return self.name

    class Meta:
        db_table = "Tag"
        verbose_name = "标签"
        verbose_name_plural = "标签"


class classification(models.Model):
    id = models.AutoField(primary_key=True, verbose_name="分类ID")
    name = models.CharField(max_length=20, verbose_name="分类名", null=True, blank=True, unique=True)

    def __str__(self):
        return self.name

    class Meta:
        db_table = "classification"
        verbose_name = "分类"
        verbose_name_plural = "分类"


class essay(models.Model):
    id = models.AutoField(primary_key=True, verbose_name="文章ID")
    title = models.CharField(max_length=100, verbose_name="标题")
    classifier = models.ForeignKey(classification, verbose_name="分类", on_delete=models.CASCADE)
    tag = models.ManyToManyField(Tag, verbose_name="标签")
    author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="作者")
    content = models.TextField(verbose_name="文章内容")
    body_html = models.TextField(verbose_name='文章内容html形式', editable=False)
    toc_html = models.TextField(verbose_name='文章目录html形式', editable=False)
    excerpt = models.TextField(verbose_name="摘要")
    create_time = models.DateTimeField(auto_now_add=True, verbose_name="发布时间")
    modify_time = models.DateTimeField(auto_now=True, verbose_name="修改时间")

    def __str__(self):
        tags_names = ",".join([tag.name for tag in self.tag.all()])
        return (
            f"文章ID:{self.id}, 文章标题:{self.title}, 分类:{self.classifier}, 标签:{tags_names}, 作者:{self.author}, "
            f"文章内容:{self.content}, 发布时间:{self.create_time}")

    def save(self, *args, **kwargs):
        # TODO: 自动生成摘要
        # 1. 把md的文本内容转换成html的字符串
        md = markdown.Markdown(extensions=[
            'markdown.extensions.extra',
            'markdown.extensions.codehilite',
            'markdown.extensions.toc',
            TocExtension(slugify=slugify)
        ])
        self.body_html = md.convert(self.content)
        self.toc_html = md.toc
        # 2. 把html的字符串中html标签通过strip_tags给剔除掉
        # 3. 提取出前54个字符串作为摘要的内容
        self.excerpt = strip_tags(self.body_html)[:500]
        super().save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('detail', args=[self.id])

    class Meta:
        db_table = "essay"
        verbose_name = "文章信息"
        verbose_name_plural = "文章信息"


def upload_image_path(instance, filename):
    return f'user/{instance.user.username}/{filename}'


class user_info(models.Model):
    id = models.AutoField(primary_key=True, verbose_name="用户ID")
    head_img = models.ImageField(upload_to=upload_image_path, verbose_name="头像")
    user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name="用户")
    age = models.IntegerField(default=0, verbose_name="年龄")
    phone = models.CharField(max_length=11, verbose_name="手机号", default="12345678901")
    desc = models.TextField(verbose_name="个人简介", default="这个人很懒，什么都没写！")

    def __str__(self):
        return f'用户名:{self.user}, 年龄:{self.age}, 手机号:{self.phone}, 简介:{self.desc}'

    class Meta:
        verbose_name = "用户信息"
        verbose_name_plural = verbose_name


class Comment(models.Model):
    id = models.AutoField(primary_key=True, verbose_name="评论ID")
    article = models.ForeignKey(essay, related_name='comments', on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    text = models.TextField()
    liked_users = models.ManyToManyField(User, related_name='liked_comments', blank=True)
    like_count = models.IntegerField(default=0, verbose_name="点赞数")
    parent = models.ForeignKey('self', null=True, blank=True, related_name='replies', on_delete=models.CASCADE)

    create_time = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f'{self.user.username}: {self.text}'

    def get_absolute_url(self):
        return reverse('submit_reply', args=self.id)

    class Meta:
        db_table = "Comment"
        verbose_name = "评论"
        verbose_name_plural = "评论"


class CommentLike(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    comment = models.ForeignKey(Comment, on_delete=models.CASCADE)

    class Meta:
        unique_together = ('user', 'comment')


class Student(models.Model):
    name = models.CharField('名字', max_length=100)

    age = models.IntegerField('年龄')

    class Meta:
        verbose_name = "学生"
        verbose_name_plural = verbose_name

    def __str__(self):
        return '{}-{}'.format(self.name, self.age)
